import {
	defineStore
} from "pinia";
import {
	setToken,
	setUserinfo,
	getUserinfo,
	removeToken,
	removeUserinfo,
	showToast,
} from "@/utils/common.js";
import {
	userCodeLogin,
} from "@/api/login/index.js";
import {
	getUserInfo
} from "@/api/user"

export default defineStore("user", {
	state: () => ({
		userInfo: getUserinfo(),
		systemInfo: null, // 系统信息
		isIOS: false,
		autoLogin: false,
	}),
	actions: {

		Auto_login(params) {
			return new Promise(async (resolve, reject) => {
				try {
					let res = await userCodeLogin(params)
					// let res={
					// 	token:"d183935e69371977ffe01c5475930587"
					// }
					let {
						token,
					} = res
					setToken(token)
					setUserinfo(res);
					uni.$emit('login-success');
					await this.getUserInfo()
					resolve(res)
				} catch (e) {
					console.log("Auto_login错误", e)
					if (e && e.info) {
						showToast(e.info)
					}
					reject(e)
				}
			})
		},
		async getUserInfo() {
			try {
				let res = await getUserInfo()
				// setToken(res.token);
				setUserinfo(res);
				this.userInfo = res;
			} catch (error) {
				console.log("获取用户信息失败");
			}
		},
		setUserInfo(data) {
			this.userInfo = data;
			setUserinfo(data);
		},
		LogOut() {
			this.setUserInfo({});
			removeUserinfo();
			removeToken();
			uni.$emit("index-collection-list")
		},
		Get_system_info() {
			let res = uni.getSystemInfoSync();
			console.log("getSystemInfoSync", res);
			this.systemInfo = res;
			let {
				platform
			} = res;
			this.isIOS = platform === "ios";
		},
	},
	// getters: {
	// 	userInfo: state => state.userInfo
	// }
});